package com.djj.nanny.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import com.djj.nanny.common.Result;
import com.djj.nanny.entity.AlipayProperties;
import com.djj.nanny.entity.ServiceItem;
import com.djj.nanny.entity.ServiceOrder;
import com.djj.nanny.service.ServiceItemService;
import com.djj.nanny.service.ServiceOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

@Tag(name = "订单管理接口")
@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class ServiceOrderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceOrderController.class);

    @Resource
    private ServiceOrderService orderService;

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradePagePayRequest payRequest;

    @Resource
    private AlipayProperties alipayProperties;

    @Resource
    private ServiceItemService serviceItemService;

    @Operation(summary = "创建订单")
    @PostMapping
    public Result<?> createOrder(@RequestBody @Valid ServiceOrder order) {
        LOGGER.info("创建订单: userId={}, staffId={}", order.getUserId(), order.getStaffId());
        orderService.createOrder(order);
        return Result.success("创建成功");
    }

    @Operation(summary = "更新订单状态")
    @PutMapping("/{id}/status")
    public Result<?> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            @RequestParam(required = false) String reason) {
        LOGGER.info("更新订单状态: {}, status: {}", id, status);
        orderService.updateOrderStatus(id, status, reason);
        return Result.success("状态更新成功");
    }

    @SneakyThrows
    @PostMapping("/{id}/pay")
    public Result<?> pay(
            @PathVariable Long id) {

        ServiceOrder order = orderService.getOrderById(id);
        ServiceItem serviceItem = serviceItemService.getServiceItemById(order.getServiceId());

        JSONObject bizContent = new JSONObject();

        bizContent.put("out_trade_no", order.getId());
        bizContent.put("subject", serviceItem.getTitle());
        bizContent.put("total_amount", order.getTotalAmount());
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY");
        bizContent.put("timeout_express","15m");
        payRequest.setBizContent(bizContent.toString());

        // 向支付宝发起支付请求
        String result = alipayClient.pageExecute(payRequest).getBody();
        // 将结果返回给前端，进入支付宝用户登录页面
        return Result.success(result);
    }

    /**
     * 异步通知
     */
    @PostMapping("/notify")
    public Result<?> notify(@RequestParam Map<String,String> params) throws AlipayApiException {
        System.out.println(params);
        /**
         * 进行验签操作，防止签名被篡改
         */
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if(!flag){
            log.info("验证签名失败！");
            return Result.error("fail");
        }

        /**
         * 判断返回的订单号、订单总金额等是否与发送的一致，防止数据被篡改
         */
        String out_trade_no = params.get("out_trade_no");
        String total_amount = params.get("total_amount");

        ServiceOrder order = orderService.getOrderById(Long.parseLong(out_trade_no));
        if(Objects.isNull(order)) {
            log.info("订单不存在！");
            return Result.error("订单支付失败");
        }
        
        // 使用BigDecimal比较金额，避免精度问题
        BigDecimal orderAmount = order.getTotalAmount();
        BigDecimal payAmount = new BigDecimal(total_amount);
        if(orderAmount.compareTo(payAmount) != 0) {
            log.info("订单金额不一致！订单金额：{}，支付金额：{}", orderAmount, payAmount);
            return Result.error("订单支付失败");
        }

        /**
         * 判断支付宝返回的状态是否正常
         */
        String trade_status = params.get("trade_status");
        if(!trade_status.equals("TRADE_SUCCESS")){
            log.info("交易失败！");
            return Result.error("订单支付失败");
        }

        /**
         * 更新相应的订单状态，例如将订单标记为已支付、更新库存等
         */
        orderService.updateOrderStatus(order.getId(), 2, null);

        return Result.success("订单支付成功", null);
    }

    @Operation(summary = "获取订单详情")
    @GetMapping("/{id}")
    public Result<?> getOrder(@PathVariable Long id) {
        LOGGER.info("获取订单详情: {}", id);
        return Result.success(orderService.getOrderById(id));
    }

    @Operation(summary = "获取订单列表")
    @GetMapping("/list")
    public Result<?> getOrderList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Long staffId,
            @RequestParam(required = false) Integer status) {
        LOGGER.info("获取订单列表: pageNum={}, pageSize={}", pageNum, pageSize);
        return Result.success(orderService.getOrdersByPage(userId, staffId, status, pageNum, pageSize));
    }

    @Operation(summary = "取消订单")
    @PutMapping("/{id}/cancel")
    public Result<?> cancelOrder(
            @PathVariable Long id,
            @RequestParam String reason) {
        LOGGER.info("取消订单: {}, reason: {}", id, reason);
        orderService.cancelOrder(id, reason);
        return Result.success("订单取消成功");
    }
} 